<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    /**
     * @return AdminResource
     */
    public function getProfile()
    {
        $authUser = Auth::user();
        return new AdminResource($authUser);
    }
    /**
     * 当前登录为总公司管理员就返回所有数据，若为分公司管理员，就返回分公司对应的管理员
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $query = Admin::query();
        $models = $query->when($keyword, function ($queryString) use ($keyword) {
            return $queryString->where('name', 'like', '%' . $keyword . '%');
        })->orderByDesc('id')->paginate();
        return AdminResource::collection($models);
    }

    /**
     * @param Request $request
     * @return AdminResource
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $roles = $request->get('permissions');
        $model = new Admin();
        $model->fill($data);
        $model->password = bcrypt($data['password']);
        $model->save();
        $model->roles()->sync($roles);
        return new AdminResource($model);
    }

    /**
     * @param Admin $admin
     * @return AdminResource
     */
    public function show(Admin $admin)
    {
        return new AdminResource($admin);
    }

    /**
     * @param Request $request
     * @param $id
     * @return AdminResource
     */
    public function update(Request $request, $id)
    {
        $admin = $this->findModel($id);
        $roles = $request->get('permissions');
        $admin->fill($request->all());
        $admin->save();
        $admin->roles()->sync($roles);
        return new AdminResource($admin);
    }

    /**
     * @param $adminId
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($adminId)
    {
        $model = $this->findModel($adminId);
        $model->delete();
        return response()->json(['state' => 'success']);
    }

    /**
     * @param $adminId
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function findModel($adminId)
    {
        $model = Admin::query()->findOrFail($adminId);
        return $model;
    }

}
